#encoding=utf-8
'''
Created on 2011-11-21

@author: guanyw

python version:2.6
'''
from corpus.preprocess import translate_number, sentence_to_triple_list, rep_num,\
    untag_sentence
import re
    

def get_numbers(txt):
    
    num_list = u'[0123456789零两一二三四五六七八九]'
    txt = rep_num(txt)
    ret = [wd for wd,pos,nes in sentence_to_triple_list(txt) 
            if pos in ['/n','/m'] and re.findall(num_list,wd)]
    return ret

def bigger(hyp,txt_n):
    bigger_word = [u'超过',u'大于',u'高于',u'多于']
    h_right = re.sub('.*?(' + r'|'.join(bigger_word)+')',u'超过',hyp,re.DOTALL)
#    print h_right
    hyp_nr = [re.sub('[^0-9]', '', translate_number(n, 'n')) for n in get_numbers(h_right)]
    txt_nn = txt_n.copy()
    if hyp_nr:
#        print hyp_nr
#        print '\t'.join(txt_n)
        for ns in txt_n:
            tnp = re.findall('\d+', ns)
            bfnd= False
            for hr in hyp_nr:
                if tnp and hr and int(tnp[0]) >= int(hr):
    #                print re.sub('\d+',h_bigr[0][1],ns)
                    txt_nn.add(re.sub('\d+',hr,ns))
                    bfnd = True
            if bfnd :
                break
    return txt_nn
    
def is_number_match(txt,hyp):
    
    txt_n = set([translate_number(n, 'n') for n in get_numbers(txt)])
    
    txt_n = bigger(hyp, txt_n) #extend it using some rules
    hyp_n = set([translate_number(n, 'n') for n in get_numbers(hyp)])
#    print ''.join(txt_n)
#    print ''.join(hyp_n)
    return not (hyp_n-txt_n)

def distance(str1,str2):
    m=len(str1)
    n=len(str2)
    D=[[0 for i in range(n+1)]for j in range(m+1)]
    for i in range(m+1):
        D[i][0]=i
    for i in range(n+1):
        D[0][i]=i
    for i in range(1,m+1):
        for j in range(1,n+1):
            if str1[i-1]==str2[j-1]:
                cost=0
            else:
                cost=1
            D[i][j]=min(D[i-1][j]+1,D[i][j-1]+1,D[i-1][j-1]+cost)
    return D[m][n] 

def is_first_ne_match(txt,hyp):
    
    txt_ne = [wd for wd,pos,nes in sentence_to_triple_list(txt) if nes !='/O']
    hyp_ne = [wd for wd,pos,nes in sentence_to_triple_list(hyp) if nes !='/O']

    
    if hyp_ne:
        for tn in txt_ne:
            if tn.find(hyp_ne[0])!=-1 or hyp_ne[0].find(tn)!= -1:
                return True

    txt_wd = untag_sentence(txt)
    hyp_wd = untag_sentence(hyp)
    if distance(txt_wd, hyp_wd)/float(len(hyp_wd)) < 0.9:
        return True
    
    return len(hyp_ne)==0

if __name__ == '__main__':
    pass